<template>
  <div class="login-page">
    <a-row>
      <a-col :span="12" class="aside">
        <div class="aside-inner">
          <router-link to="/">
            <img alt="Vue logo" src="@/assets/logo2.png" class="logo-img">
          </router-link>
          <h2>这是我用过的最好的建站工具</h2>
          <span class="text-white-70">王铁锤, Google</span>
        </div>
      </a-col>
      <a-col :span="12" class="login-area">
        <a-form
          :model="form" :rules="rules"
          ref="loginForm" layout="vertical"
        >
          <h2>欢迎回来</h2>
          <p class="subTitle">使用手机号码和验证码登录到慕课乐高</p>
          <a-form-item label="手机号码" name="username">
            <a-input v-model:value="form.username" placeholder="手机号码">
              <template v-slot:prefix><UserOutlined style="color:rgba(0,0,0,.25)"/></template>
            </a-input>
          </a-form-item>
          <a-form-item label="验证码" required name="veriCode">
            <a-input v-model:value="form.veriCode" placeholder="四位验证码">
              <template v-slot:prefix><LockOutlined style="color:rgba(0,0,0,.25)"/></template>
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="login" size="large"
              :loading="isOpLoading"
            >
              {{ isOpLoading ? '加载中' : '登录'}}
            </a-button>
            <a-button @click="getCode" size="large"
              :style="{ marginLeft: '20px' }" :disabled="codeButtonDisable || isGetCodeLoading"
              :loading="isGetCodeLoading"
            >
              {{ counter === 60 ? '获取验证码' : `${counter}秒后重发` }}
            </a-button>
          </a-form-item>
        </a-form>
      </a-col>
    </a-row>
  </div>

</template>
  
  <script setup lang="ts" name="Login">
  import { onMounted, computed, ref, reactive,watch, type Ref } from 'vue'
  import { userInfos } from '@/stores/user'
  import pinia from '@/stores/index'
  import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'

  import { useRoute, useRouter } from 'vue-router';
  import { isMobile } from '@/constant/helper'
  import type { Rule } from 'ant-design-vue/es/form';
  import axios from 'axios'
  import { Form, message } from 'ant-design-vue';
  import { formatAxis } from '@/utils/formatTime';
  import { NextLoading } from '@/utils/loading';
  import {authApi} from '@/api/auth'

  import { gloabl } from '@/stores/global'

  const userInfoStore = userInfos(pinia)
  const globalStore = gloabl(pinia)

  const useForm = Form.useForm;
  interface RuleFormInstance {
  validate: () => Promise<any>;
}
  const isLoading = computed(()=>globalStore.isLoading)
  const isOpLoading = computed(()=> globalStore.isOpLoading('login'))
  const isGetCodeLoading = computed(()=> globalStore.isOpLoading('getCode'))

  const route = useRoute();
  const router = useRouter();
  const counter = ref(60)
  let timer: any
  const form = reactive({
    username: '',
    veriCode: ''
  })
  const loginForm = ref() as Ref<RuleFormInstance>
  const status:any = {}
  const cellnumberValidator = async (rule: Rule, value: string) => {
    const passed = isMobile(value.trim())
    if (!value) {
      return Promise.reject('手机号码不能为空');
    }
    if (!passed) {
      return Promise.reject('手机号码格式不正确');
    } else {
      return Promise.resolve();
    }  
  }
      
    const startCounter = () => {
      counter.value--
      timer = setInterval(() => {
        counter.value--
      }, 1000)
    }
    watch(counter, (newValue) => {
      if (newValue === 0) {
        clearInterval(timer)
        counter.value = 60
      }
    })
    const codeButtonDisable = computed(() => {
      return !isMobile(form.username.trim()) || (counter.value < 60)
    })
    const rules = {
      username: [
        { validator: cellnumberValidator, trigger: 'change' }
      ],
      veriCode: [
        { required: true, message: '验证码不能为空', trigger: 'blur' }
      ]
    }
  // 时间获取
  const currentTime = computed(() => {
    return formatAxis(new Date());
  });
  const { resetFields, validate } = useForm(form, rules);
    const login = async() => {
      /* loginForm.value.validate().then(() => {
      }) */
      validate()
      .then( async res => {
        const payload = {
          phoneNumber: form.username,
          veriCode: form.veriCode
        }
        try {
          const loginData = await userInfoStore.login(payload)
          if (!userInfoStore.token) {
            //message.error('登陆失败')
            return
          }
          await userInfoStore.setUserInfos()
          if (userInfoStore.userInfos === null) {
            userInfoStore.logout()
            return
          }
          // 初始化登录成功时间问候语
          let currentTimeInfo = currentTime.value;
          // 登录成功，跳到转首页
          // 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中

          if (route.query?.redirect) {
            router.push({
              path: <string>route.query?.redirect,
              query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
            });
          } else {
            router.push('/');
          }
          // 登录成功提示
          message.success(`${currentTimeInfo} ${userInfoStore?.userInfos?.username}登录成功`)
          NextLoading.start();  
        } catch (error) {
          message.error('登陆状态异常，请重新尝试', 2)
          userInfoStore.logout()
        }
   
      })
      .catch(err => {
        console.log('error', err);
      });

    }
    const getCode = async() => {
      const [e,r] = await authApi.getVeriCode({ phoneNumber: form.username }, {opName: 'getCode'})
      if (r && r.errno ==0) {
        message.success('验证码已发送，请注意查收', 5)
          startCounter()
      }

    }
    onMounted(()=>{
        
    })
</script>
<style lang="scss" scoped>
  .logo-area {
    position: absolute;
    top: 30px;
    width: 150px;
  }
  .aside {
    height: 100vh;
    background-color: #1a1919;
    background-image: url('~@/assets/login.png');
    background-size: cover;
    background-repeat: no-repeat;
  }
  .aside .logo-img {
    width: 200px;
    margin-bottom: 20px;
  }
  .aside h2 {
    color: #CCCCCC;
    font-size: 29px;
  }
  .aside-inner {
    width: 60%;
    text-align: center;
  }
  .login-area {
    height: 100vh;
  }
  .login-area .ant-form {
    width: 350px;
  }
  .text-white-70 {
    color: #999;
    display: block;
    font-size: 19px;
  }
  .aside, .login-area {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .login-area h2 {
    color: #333333;
    font-size: 29px;
  }
  .login-area .subTitle {
    color: #666666;
    font-size: 19px;
  }
  .login-area .ant-form-item-label {
    display: none;
  }
  .login-area .ant-input-prefix {
    left: auto;
    right: 30px;
    font-size: 19px;
  }
  .login-area .ant-input {
    font-size: 17px;
    padding: 20px 45px 20px 30px;
    background-color: #ebf2ff;
    border-color: #ebf2ff;
  }
</style>
  